/**
 *
 */
package com.hk.Mgr.web.controller.app;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hk.commons.*;
import com.hk.context.PaymentContext;
import com.hk.service.IPush;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.order.AddCardRes;
import com.hk.Mgr.web.message.order.PaymentReq;
import com.hk.Mgr.web.message.order.PaymentRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.entity.yingmi.YingmiConfirmFile;
import com.hk.service.order.IOrderInfo;
import com.hk.service.order.IPayment;
import com.hk.service.sys.ISysUser;
import com.hk.service.yingmi.IYingmiConfirmFile;

/**
 * 更新用户的绑卡信息
 *
 * @author
 */
@Controller
@RequestMapping(value = BaseCtrl.App + "/paymentCtrl")
public class 	AppPaymentCtrl extends BaseCtrl {

	private Logger logger = LoggerFactory.getLogger(AppPaymentCtrl.class);

	@Autowired
	private ISysUser userService;

	@Autowired
	private PaymentContext paymentContext;

	@Autowired
	private IPayment paymentService;

	@Autowired
	private IOrderInfo orderInfoService;

	@Autowired
	private IYingmiConfirmFile ymConfirmService;

	@Value("${fy.Secret}")
	private String fySecret;

	@Value("${fy.mchntCd}")
	private String fyMchntCd;

	@Value("${fy.scheme}")
	private String scheme;

	@Value("${fy.valiFour}")
	private String realUrl;

	@Value("${fy.validateCardPath}")
	private String path;

	@Value("${fy.getBankPath}")
	private String getBankpath;

	@Value("${hk.logsBaseUrl}")
	private String logsBaseUrl;

	@Autowired
	private IPush pushService;
	/**
	 * 取消换卡接口
	 *
	 * @param paymentId
	 * @param otherInfo
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cancelChangeCard", method = RequestMethod.GET)
	public ResponseBase<String> cancelChangeCard(
			@RequestParam String paymentId, String otherInfo) {
		ResponseBase<String> cancelResult = new ResponseBase<String>();
		logger.info("取消换卡入参paymentId={}", paymentId);
		Long id = Long.parseLong(paymentId);
		Payment p = paymentService.findById(id);
		if (p != null) {
			int cardStatus = p.getCardStatus();
			if (CardStatusCode.FY_CHANGE_CARD_FAIL == cardStatus) {// 如果是换卡失败了，才可以取消换卡。
				p.setCardStatus(CardStatusCode.PAYMENT_DISPLAY_SHOW);
				paymentService.update(p);
				cancelResult.setResult("取消成功！该卡可以继续使用。");
				cancelResult.setResultCode(ResultCode.SUCC.getCode());
			} else {
				cancelResult.setResult("该卡没有换卡失败，不能取消！");
				cancelResult.setResultCode(ResultCode.FAILED.getCode());
				cancelResult.setMsg(ResultCode.FAILED.getMsg());
			}
		} else {
			cancelResult.setResult("不存在该卡！不能取消");
			cancelResult.setResultCode(ResultCode.NO_DATA.getCode());
			cancelResult.setMsg(ResultCode.NO_DATA.getMsg());
		}
		return cancelResult;
	}

	@ResponseBody
	@RequestMapping(value = "/unbindCard", method = RequestMethod.GET)
	// true能解，，false不能解绑 //orderinfo没有订单，可以解绑
	public ResponseBase<Boolean> unbindCard(@RequestParam String userId,
			String paymentNo, String paymentMethodId, String phone) {
		ResponseBase<Boolean> base = new ResponseBase<Boolean>();
		userId = userId.split(",")[0];
		logger.info(
				"解绑请求unbindCard入参userId={},paymentNo={},paymentMethodId={},phone={}",
				userId, paymentNo, paymentMethodId, phone);
		if ("无".equals(paymentMethodId)) {
			paymentMethodId = null;
		}
		if (StringHelper.isEmpty(userId) || StringHelper.isEmpty(paymentNo)
				|| StringHelper.isEmpty(phone)) {
			base.setResultCode(ResultCode.PARAM_ERROR.getCode());
			base.setResult(false);
			base.setMsg("参数不能为空！");
			return base;
		}
		boolean ifCanUnbind = true;
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId", Long.valueOf(userId));
		try {
			HqlFilter cardNohqlFilter = new HqlFilter();
			cardNohqlFilter.addEQFilter("paymentNo", paymentNo);
			List<Payment> noList = paymentService.findByFilter(cardNohqlFilter);
			if (noList.size() == 0) {
				base.setResultCode(ResultCode.PARAM_ERROR.getCode());
				base.setResult(false);
				base.setMsg("不存在该卡号的绑卡记录,不能解绑！");
				return base;
			}
			if (StringHelper.isNotEmpty(paymentMethodId)) {
				HqlFilter methodIdhqlFilter = new HqlFilter();
				methodIdhqlFilter.addEQFilter("paymentMethodId",
						paymentMethodId);
				List<Payment> methodList = paymentService
						.findByFilter(methodIdhqlFilter);
				if (methodList.size() == 0) {
					base.setResultCode(ResultCode.PARAM_ERROR.getCode());
					base.setResult(false);
					base.setMsg("不存在该卡号的绑卡记录,不能解绑！");
					return base;
				}
			}
			List<OrderInfo> orderInfoList = orderInfoService
					.findByFilter(hqlFilter);
			if (orderInfoList.size() > 0) {
				for (OrderInfo orderInfo : orderInfoList) {
					if (orderInfo.getPayStatus() == 2) {// 已支付成功的订单
						Long paymentId = orderInfo.getPaymentId();
						if (paymentId != null) {
							Payment curPayment = paymentService
									.findById(paymentId);
							if (curPayment != null) {
								String curPaymentNo = curPayment.getPaymentNo();
								if (paymentNo.equals(curPaymentNo)) {// 已支付成功过的订单中使用该卡号支付不能解绑
									ifCanUnbind = false;
									logger.info(
											"orderinfo表中存在该卡号的记录不能解绑，paymentNo={}",
											paymentNo);
									break;
								}
							}
						}
					}

				}
			}
			base.setResult(ifCanUnbind);
			if (ifCanUnbind) {
				base.setMsg("该卡可以解绑");
				base.setResultCode(ResultCode.SUCC.getCode());
			} else {
				base.setMsg("您的卡上有未回款订单，暂不能解绑");
				base.setResultCode(ResultCode.FAILED.getCode());
			}

		} catch (Exception e) {
			logger.error("解绑出现未知异常", e);
			base.setMsg("解绑失败");
			base.setResultCode(ResultCode.FAILED.getCode());
			base.setResult(false);
			// e.printStackTrace();
		}
		return base;
	}

	// 盈米解绑成功后回调本接口进行解绑
	@ResponseBody
	@RequestMapping(value = "/unbindYmCard", method = RequestMethod.GET)
	public ResponseBase<Boolean> unbindYmCard(@RequestParam String userId,
			String paymentNo, String paymentMethodId, String phone,
			String newApi) {

		return paymentContext.unbindYmCard(userId,paymentNo,paymentMethodId,phone);
	}


	/**
	 * 盈米绑卡数据返回接口
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ResponseBase<AddCardRes> add(@RequestBody PaymentReq req) {

		return paymentContext.addCard(req);

	}

	/**
	 * 根据用户id 获取银行卡信息
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getList", method = RequestMethod.POST)
	public ResponseBase<List<PaymentRes>> getList(@RequestBody PaymentReq req) {
		Long userId =req.getUserId();
		ResponseBase<List<PaymentRes>> resp = new ResponseBase<List<PaymentRes>>();
		List<PaymentRes> payResList = new ArrayList<PaymentRes>();
		if (userId != null) {
			try {
				List<Payment> payList = new ArrayList<Payment>();
				HqlFilter hqlFilter = new HqlFilter();
				hqlFilter.addEQFilter("userId", userId);
				hqlFilter.addSql(" and cardStatus in ("
						+ CardStatusCode.PAYMENT_DISPLAY_SHOW + ","
						+ CardStatusCode.FY_CHANGE_CARD_FAIL + ","
						+ CardStatusCode.FY_CHANGE_CARDING + ")");
				payList = paymentService.findByFilter(hqlFilter);
				logger.info("该用户userId={},共有卡数：cardNo={}", userId,
						payList.size());
				if (payList.size() == 1) {// 用户只有一张卡，不用判断金额直接返回
					addResultPayment(payResList, payList.get(0), false, 4);
					resp.setResultCode(ResultCode.SUCC.getCode());
					resp.setResult(payResList);
					resp.setSize(payResList.size());
				} else if (payList.size() == 0) {// 用户没有绑卡
					resp.setResultCode(ResultCode.SUCC.getCode());
					resp.setResult(payResList);
					resp.setSize(payResList.size());
				} else {// 多张卡处理
					Map<Object, BigDecimal> paymentMoneyMap = new HashMap<Object, BigDecimal>();// 卡关键字和卡总金额map
					for (Payment pay : payList) {
						HqlFilter orderFilter = new HqlFilter();
						Long paymentId = pay.getId();
						orderFilter.addEQFilter("paymentId", paymentId);
						List<OrderInfo> orderList = orderInfoService
								.findByFilter(orderFilter);
						if (orderList.size() > 0) {// 优先选择富友支付订单和火柴支付订单的卡
							qryOrderInfoCard(paymentMoneyMap, orderList,
									paymentId);
						} else {// 查看盈米订单
							if (StringHelper.isNotEmpty(req.getPhone())) {
								List<YingmiConfirmFile> ymList = getYingmiOrder(req
										.getPhone());
								if (ymList.size() > 0) {
									qryYingmiCard(paymentMoneyMap, ymList,
											userId);
								} else {
									logger.info(
											"该用户此卡没有任何订单，userId={}，paymentId={}",
											userId, paymentId);
								}
							} else {
								logger.info("入参phone为空，无法查询盈米订单");
							}
						}
					}
					if (!paymentMoneyMap.isEmpty()) {
						Payment maxpayment = null;
						maxpayment = getBestCard(paymentMoneyMap, userId);
						if (maxpayment != null) {// 添加消费金额最多的卡为list的第一张卡
							addResultPayment(payResList, maxpayment, true, 4);
						}
						for (Payment pay2 : payList) {
							if (maxpayment != null) {
								if (pay2.getId().longValue() != maxpayment
										.getId().longValue()) {// 添加其余的卡
									addResultPayment(payResList, pay2, false, 4);
								}
							} else {
								addResultPayment(payResList, pay2, false, 4);
							}
						}
						resp.setSize(payResList.size());
						resp.setResult(payResList);
						resp.setResultCode(ResultCode.SUCC.getCode());
					} else {
						if (payList.size() > 0) {
							for (Payment noPayment : payList) {
								addResultPayment(payResList, noPayment, false,
										4);
							}
							resp.setSize(payList.size());
							resp.setResult(payResList);
							resp.setResultCode(ResultCode.SUCC.getCode());
						}
					}
				}
			} catch (Exception e) {
				logger.error("获取银行卡列表出现未知异常", e);
				resp.setResult(payResList);
				resp.setResultCode(ResultCode.FAILED.getCode());
			}
		} else {
			logger.error("userId为空");
			resp.setResult(payResList);
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
		}
		return resp;
	}

	/**
	 * 根据用户id 获取银行卡信息
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getAllChannelList", method = RequestMethod.POST)
	public ResponseBase<List<PaymentRes>> getAllChannelList(
			@RequestBody PaymentReq req) {
		//Long userId = CheckUserId.checkId(req.getUserId());
		Long userId =req.getUserId();
		ResponseBase<List<PaymentRes>> resp = new ResponseBase<List<PaymentRes>>();
		List<PaymentRes> payResList = new ArrayList<PaymentRes>();

		//限制销户用户-2.7.6
		SysUser user = userService.findById(userId);
		if(user == null || user.getCloseAccount() ==1){
			resp.setResult(null);
			resp.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
			resp.setMsg(ResultCode.USER_NOT_EXIST.getMsg());
			return resp;
		}

		if (userId != null) {
			try {
				List<Payment> payList = new ArrayList<Payment>();
				HqlFilter hqlFilter = new HqlFilter();
				hqlFilter.addEQFilter("userId", userId);
				payList = paymentService.findByFilter(hqlFilter);
				logger.info("该用户userId={},共有卡数：cardNo={}", userId,
						payList.size());
				for (Payment p : payList) {
					String supportCompanys = p.getSupportCompany();
					String[] companys = supportCompanys.split(",");
					for (int i = 0; i < companys.length; i++) {
						String currentCompany = companys[i];
						if (("" + ConstantRoute.COMPANY_HUAKANG)
								.equals(currentCompany)
								|| ("" + ConstantRoute.COMPANY_HUOCHAI)
										.equals(currentCompany)
								|| ("" + ConstantRoute.COMPANY_YINGMI)
										.equals(currentCompany)
								|| ("" + CardStatusCode.UNBIND_CARD)
										.equals(currentCompany)) {// 已解绑过的。

							p.setSupportCompany(currentCompany);
							addResultPayment(payResList, p, false, i + 1);
						}
					}
				}
				resp.setSize(payResList.size());
				resp.setResult(payResList);
				resp.setResultCode(ResultCode.SUCC.getCode());
			} catch (Exception e) {
				logger.error("获取银行卡列表出现未知异常", e);
				resp.setResult(payResList);
				resp.setResultCode(ResultCode.FAILED.getCode());
			}
		} else {
			logger.error("userId为空");
			resp.setResult(payResList);
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
			resp.setMsg(ResultCode.PARAM_ERROR.getMsg());
		}
		return resp;
	}


	/**
	 * 根据用户id 获取用户单张银行卡信息
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getUserPaymentInfo", method = RequestMethod.POST)
	public ResponseBase<PaymentRes> getUserPaymentInfo(
			@RequestBody PaymentReq req) {

		ResponseBase<PaymentRes> resp = new ResponseBase<>();

		try{
			if (req == null || req.getUserId() == null) {
				logger.error("userId为空");
				resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
				resp.setMsg(ResultCode.PARAM_ERROR.getMsg());
			}

			Long userId =req.getUserId();

			List<Payment> payList = new ArrayList<Payment>();
			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("userId", userId);
			hqlFilter.addEQFilter("cardStatus", 1);
			payList = paymentService.findByFilter(hqlFilter);


			if (payList == null || payList.size() == 0) {
				resp.setResultCode(ResultCode.NO_DATA.getCode());
				resp.setMsg(ResultCode.NO_DATA.getMsg());
				return resp;
			}

			Payment pay = payList.get(0);

			PaymentRes paymentRes = new PaymentRes();
			paymentRes.setAccountName(pay.getAccountName());
			paymentRes.setPhone(pay.getPhone());
			paymentRes.setIdentityNo(pay.getIdentityNo());
			paymentRes.setPaymentNo(pay.getPaymentNo());

			resp.setResult(paymentRes);
			resp.setResultCode(ResultCode.SUCC.getCode());
			return  resp;
		} catch (Exception e) {
			logger.error("获取银行卡列表出现未知异常", e);
			resp.setResultCode(ResultCode.FAILED.getCode());
		}

		return resp;
	}


	private List<YingmiConfirmFile> getYingmiOrder(String phone) {
		List<YingmiConfirmFile> ymList = new ArrayList<YingmiConfirmFile>();
		HqlFilter ymFilter = new HqlFilter();
		ymFilter.addEQFilter("brokerUserId", phone);
		try {
			ymList = ymConfirmService.findByFilter(ymFilter);
		} catch (Exception e) {
			logger.error("appPaymentCtr查询盈米订单失败", e);
			// e.printStackTrace();
		}

		return ymList;
	}

	private Payment getBestCard(Map<Object, BigDecimal> paymentMoneyMap,
			Long userId) {
		Payment maxpayment = null;
		Object maxKey = "";
		BigDecimal maxAcount = new BigDecimal(0);
		boolean hasOurCard = false;
		for (Object key : paymentMoneyMap.keySet()) {
			logger.info("卡和消费对应情况key={},money={}", key,
					paymentMoneyMap.get(key));
			if (key instanceof Long) {
				hasOurCard = true;
			}
		}
		for (Object key : paymentMoneyMap.keySet()) {
			if ((hasOurCard && (key instanceof Long))
					|| ((!hasOurCard) && (key instanceof String))) {
				if (paymentMoneyMap.get(key).compareTo(maxAcount) == 1) {// 前者大于后者
					maxAcount = paymentMoneyMap.get(key);
					maxKey = key;
				}
			}
		}
		logger.info("使用金额最大的卡为maxKey={},money={}", maxKey, maxAcount);
		if (maxKey instanceof Long) {
			maxpayment = paymentService.findById((Long) maxKey);
		} else if (maxKey instanceof String) {
			HqlFilter methodIdFilter = new HqlFilter();
			methodIdFilter.addEQFilter("paymentMethodId", maxKey);
			methodIdFilter.addEQFilter("userId", Long.valueOf(userId));
			List<Payment> paymentList = paymentService
					.findByFilter(methodIdFilter);
			if (paymentList.size() > 0) {
				maxpayment = paymentList.get(0);
			}
		} else if (maxKey == null) {
			logger.info("maxKey is null");
		}

		return maxpayment;
	}

	private void qryYingmiCard(Map<Object, BigDecimal> paymentMoneyMap,
			List<YingmiConfirmFile> ymList, Long userId) {
		logger.info("该用户在盈米确认表有订单,userId={}", userId);
		for (YingmiConfirmFile yingmiConfirmFile : ymList) {
			String ympaymentMethodId = yingmiConfirmFile.getPaymentMethodId();
			BigDecimal ymsuccAmount = yingmiConfirmFile.getSuccAmount();
			if (ymsuccAmount != null
					&& (StringHelper.isNotEmpty(ympaymentMethodId))) {
				if (paymentMoneyMap.containsKey(ympaymentMethodId)) {
					BigDecimal ymOldMoney = paymentMoneyMap
							.get(ympaymentMethodId);
					ymsuccAmount = ymsuccAmount.add(ymOldMoney);
				}
				paymentMoneyMap.put(ympaymentMethodId, ymsuccAmount);
			} else {
				logger.info(
						"ympaymentMethodId或金额为空！ympaymentMethodId={}，ymsuccAmount={}",
						ympaymentMethodId, ymsuccAmount);
			}

		}
	}

	private void qryOrderInfoCard(Map<Object, BigDecimal> paymentMoneyMap,
			List<OrderInfo> orderList, Long paymentId) {
		for (OrderInfo orderInfo : orderList) {
			BigDecimal successAmount = orderInfo.getSuccessAmount();
			if (successAmount != null) {
				if (paymentMoneyMap.containsKey(paymentId)) {
					successAmount = successAmount.add(paymentMoneyMap
							.get(paymentId));
				}
				paymentMoneyMap.put(paymentId, successAmount);
			}
		}
	}

	private void addResultPayment(List<PaymentRes> payResList,
			Payment maxpayment, boolean index, int i) {
		PaymentRes paymentRes = new PaymentRes();
		String accountName = maxpayment.getAccountName();
		String phone = maxpayment.getPhone();
		String paymentNo = maxpayment.getPaymentNo();
		String identityNo = maxpayment.getIdentityNo();
		paymentRes.setPaymentId(String.valueOf(maxpayment.getId()));
		paymentRes.setAccountName(accountName);
		paymentRes.setAccountNameEncry(maxpayment.getEncryptAccountName());
		paymentRes.setPaymentNo(paymentNo);
		paymentRes.setPaymentNoEncry(maxpayment.getEncryptPaymentNo());
		paymentRes.setPhone(phone);
		paymentRes.setPhoneEncry(maxpayment.getEncryptPhone());
		paymentRes.setIdentityNo(identityNo);
		paymentRes.setPaymentMethodId(maxpayment.getPaymentMethodId());
		paymentRes.setIdentityNoEncry(maxpayment.getEncryptIdentityNo());
		paymentRes.setBankName(maxpayment.getBankName());
		paymentRes.setBankOrgId(maxpayment.getInsCard());
		paymentRes.setCardType(maxpayment.getCardType());
		paymentRes.setSupportCompany(maxpayment.getSupportCompany());
		paymentRes.setCardStatus(maxpayment.getCardStatus());
		paymentRes.setExtraInfo(maxpayment.getExtraInfo());
		paymentRes.setChangeCardResult(maxpayment.getChangeCardResult());

		switch (i) {
		case 1:
			paymentRes.setCompany("" + ConstantRoute.COMPANY_HUAKANG);
			break;
		case 2:
			paymentRes.setCompany("" + ConstantRoute.COMPANY_HUOCHAI);
			break;
		case 3:
			paymentRes.setCompany("" + ConstantRoute.COMPANY_YINGMI);
			break;
		default:
			break;
		}
		if (index) {
			payResList.add(0, paymentRes);
		} else {
			payResList.add(paymentRes);
		}

	}

}
